﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Paradoxlost.WebParts.Microsoft.Exchange;

namespace Paradoxlost.WebParts.Calendar
{
	class CalendarView
	{
		public DateTime StartDate { get; set; }
		public DateTime EndDate { get; set; }
		public int MaxItems { get; set; }
		public string MailBox { get; set; }

		protected ExchangeServiceBinding ExchangeService { get; set; }

		public CalendarView(ExchangeServiceBinding exchange)
		{
			//MaxItems = 100;
			ExchangeService = exchange;
		}

		public CalendarView(ExchangeServiceBinding exchange, DateTime start, DateTime end)
			: this(exchange)
		{
			StartDate = start;
			EndDate = end;
		}

		protected CalendarViewType GetCalendarView()
		{
			CalendarViewType cvt = new CalendarViewType();
			cvt.StartDate = StartDate;
			cvt.EndDate = EndDate;
			if (MaxItems > 0)
			{
				cvt.MaxEntriesReturned = MaxItems;
				cvt.MaxEntriesReturnedSpecified = true;
			}
			return cvt;
		}

		protected void LoadCategoryList()
		{
			// TODO: Try to get working later

			//FindItemType request = new FindItemType()
			//{
			//    ParentFolderIds = new DistinguishedFolderIdType[]
			//    {
			//        // Specify the calendar folder
			//        new DistinguishedFolderIdType()
			//        {
			//            Id = DistinguishedFolderIdNameType.calendar,
			//            Mailbox = string.IsNullOrEmpty(this.MailBox) ?
			//                null :
			//                new EmailAddressType() { EmailAddress = this.MailBox }
			//        }
			//    },
			//    // Don't query sub folders
			//    Traversal = ItemQueryTraversalType.Shallow,
			//    // Date range
			//    //Item = new Cale
			//    // Get id and the specific property
			//    ItemShape = new ItemResponseShapeType()
			//    {
			//        BaseShape = DefaultShapeNamesType.IdOnly,
			//        //AdditionalProperties = new BasePathToElementType[]
			//        //{
			//        //    // Label Color (Exchange 2003)
			//        //    // TODO: Update for Exchange 2007
			//        //    new PathToExtendedFieldType()
			//        //    {
			//        //        PropertyId = 0x7C08,
			//        //        PropertyIdSpecified = true,
			//        //        PropertySetId = "00062002-0000-0000-C000-000000000046",
			//        //        PropertyType = MapiPropertyTypeType.Integer
			//        //    }
			//        //}
			//    },
			//    // Filter to the specific message class
			//    Restriction = new RestrictionType()
			//    {
			//        Item = new IsEqualToType()
			//        {
			//            FieldURIOrConstant = new FieldURIOrConstantType()
			//            {
			//                Item = new ConstantValueType() { Value = "IPM.Configuration.CategoryList" }
			//            },
			//            Item = new PathToUnindexedFieldType()
			//            {
			//                FieldURI = UnindexedFieldURIType.itemItemClass
			//            }
			//        }
			//    }
			//};

			//try
			//{
			//    FindItemResponseType response = this.ExchangeService.FindItem(request);
			//    FindItemResponseMessageType message = (FindItemResponseMessageType)response.ResponseMessages.Items[0];

			//    if (message.ResponseClass == ResponseClassType.Success)
			//    {
			//        ArrayOfRealItemsType messageItems = (ArrayOfRealItemsType)message.RootFolder.Item;
			//        if (messageItems.Items != null)
			//        {
			//            for (int i = 0; i < messageItems.Items.Length; i++)
			//            {
			//                ItemType item = messageItems.Items[i];
			//            }
			//        }
			//    }
			//}
			//catch (Exception ex)
			//{
			//}

		}

		public CalendarItem[] GetItems()
		{
			LoadCategoryList();

			List<CalendarItem> items = null;

			FindItemType request = new FindItemType()
			{
				ParentFolderIds = new DistinguishedFolderIdType[]
				{
					// Specify the calendar folder
					new DistinguishedFolderIdType()
					{
						Id = DistinguishedFolderIdNameType.calendar,
						Mailbox = string.IsNullOrEmpty(this.MailBox) ?
							null :
							new EmailAddressType() { EmailAddress = this.MailBox }
					}
				},
				// Don't query sub folders
				Traversal = ItemQueryTraversalType.Shallow,
				// Date range
				Item = GetCalendarView(),
				// Get everything
				ItemShape = new ItemResponseShapeType()
				{
					BaseShape = DefaultShapeNamesType.AllProperties,
					AdditionalProperties = new BasePathToElementType[]
					{
						// Label Color (Exchange 2003)
						// TODO: Update for Exchange 2007
						new PathToExtendedFieldType()
						{
							PropertyId = 0x8214,
							PropertyIdSpecified = true,
							PropertySetId = "00062002-0000-0000-C000-000000000046",
							PropertyType = MapiPropertyTypeType.Integer
						}
					}
				}
			};

			try
			{
				FindItemResponseType response = this.ExchangeService.FindItem(request);
				FindItemResponseMessageType message = (FindItemResponseMessageType)response.ResponseMessages.Items[0];

				if (message.ResponseClass == ResponseClassType.Success)
				{
					ArrayOfRealItemsType messageItems = (ArrayOfRealItemsType)message.RootFolder.Item;
					items = new List<CalendarItem>(message.RootFolder.TotalItemsInView);

					for (int i = 0; i < messageItems.Items.Length; i++)
					{
						ItemType item = messageItems.Items[i];

						items.Add(new CalendarItem((CalendarItemType)item));
					}
				}
			}
			catch (Exception ex)
			{
			}

			return items == null ? null : items.ToArray();
		}
	}
}
